<template>
  <div class="qusetion-form">
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="100px"
      class="demo-form"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="试卷名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="试卷分类" prop="paperClassId">
            <ClassifySelect
              :defaultValue="form.paperClassId"
              type="1"
              placeholder="请选择试卷分类"
              @emit="(v) => (form.paperClassId = v)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="访问权限">
            <el-select
              v-model="form.permission"
              placeholder="请选择访问权限"
              style="width: 100%"
            >
              <el-option label="完全私有" value="1"></el-option>
              <el-option label="只读共享" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="试卷状态">
        <el-radio-group v-model="form.status">
          <el-radio label="1">正常</el-radio>
          <el-radio label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <TastChapter
        :chapterList="form.testPaperChapterList"
        :paperType="form.paperType"
        ref="tastChapter"
      />
      <el-form-item>
        <el-button type="custom" @click="submitForm('form')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  components: {
    ClassifySelect: () => import('../public/ClassifySelect.vue'),
    TastChapter: () => import('./TastChapter.vue'),
  },
  data() {
    return {
      form: {
        name: '', //试卷名称
        status: '1', //状态，1-正常，2-禁用
        permission: '1', //状态，1-完全私有，2-只读共享，3-其它
        paperClassId: '', //试卷分类id
        paperType: '1', //试卷类型，1-普通试卷（试卷相同），2-随机试卷（系统分配不同试题）
        testPaperChapterList: [], //试卷章集合
        totalScore: '0', //试卷总分
        extFiled1: '', //扩展字段
      },
      rules: {
        name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
        paperClassId: [
          { required: true, message: '请选择试卷分类', trigger: 'change' },
        ],
      },
      listQuery: {
        page: 1,
        limit: 10,
        pid: 0,
        classType: 1,
      },
    }
  },
  props: ['paperType'],
  computed: {
    activeRow() {
      return this.$store.state.question.activeRow
    },
  },
  watch: {
    activeRow: {
      immediate: true,
      handler(row) {
        this.init(row)
      },
    },
    //试卷类型
    paperType: {
      immediate: true,
      handler(val) {
        this.form.paperType = val || this.activeRow.paperType
      },
    },
  },
  mounted() {},
  methods: {
    //显示弹窗
    init(row) {
      if (row.hasOwnProperty('id')) {
        this.form = { ...this.form, ...row }
        this.$set(this.form, 'id', row.id)
      } else {
        this.form = this.$options.data().form
        this.$delete(this.form, 'id')
      }
    },
    submitForm(formName) {
      this.form.totalScore = this.$refs.tastChapter.totalScore
      let testPaperChapterList = this.$refs.tastChapter.testPaperChapterList
      testPaperChapterList.forEach((item, idx) => {
        item.orderBy = ++idx
        item.testSubjectVO.forEach((v, i) => {
          v.orderBy = ++i
        })
      })
      this.form.testPaperChapterList = testPaperChapterList
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.verifyForm()
        }
      })
    },
    async verifyForm() {
      let { paperType, testPaperChapterList } = this.form
      if (!testPaperChapterList.length) {
        this.warnMsg('请添加章节')
        return
      }
      if (paperType == 1) {
        for (var i = 0; i < testPaperChapterList.length; i++) {
          let { title, testSubjectVO } = testPaperChapterList[i]
          if (!title) {
            this.warnMsg('章节名称不能为空')
            return
          } else if (!testSubjectVO.length) {
            this.warnMsg(`请在章节${title}下添加试题`)
            return
          }
          //验证每一题分值
          for (var j = 0; j < testSubjectVO.length; j++) {
            let { score } = testSubjectVO[j]
            score = parseFloat(score)
            if (!score || score <= 0) {
              this.warnMsg('试题分值不能小于等于0')
              return
            }
          }
        }
      } else {
        for (var i = 0; i < testPaperChapterList.length; i++) {
          let { title, testSubjectVO } = testPaperChapterList[i]
          if (!title) {
            this.warnMsg('章节名称不能为空')
            return
          }
          let { bankIds, score, subjectDifficulty, subjectNum, subjectType } =
            testSubjectVO[0].ruleVo
          if (!bankIds.length) {
            this.warnMsg(`请在章节${title}下添加题库`)
            return
          } else if (!subjectType) {
            this.warnMsg(`请在章节${title}下选择题型`)
            return
          } else if (!subjectDifficulty) {
            this.warnMsg(`请在章节${title}下选择难度`)
            return
          }
          subjectNum = parseInt(subjectNum)
          if (!subjectNum || subjectNum <= 0) {
            this.warnMsg(`章节${title}下题目数量不能小于等于0`)
            return
          }
          score = parseFloat(score)
          if (!score || score <= 0) {
            this.warnMsg(`章节${title}下单题分值不能小于等于0`)
            return
          }
        }
      }
      //删除testSubjects
      testPaperChapterList.forEach((item) => {
        item.testSubjectVO.forEach((v) => {
          this.$delete(v, 'testSubjects')
        })
      })
      let dispatchType = this.activeRow.hasOwnProperty('id')
        ? 'testPaperUPDATE'
        : 'testPaperADD'
      await this.$store.dispatch(dispatchType, this.form)
      this.$store.commit('SET_ACTIVENAME', 'manage')
    },
  },
}
</script>
<style scoped>
.qusetion-form {
  max-width: 900px;
}
</style>